package dao;

import model.User;
import util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 对用户表相关的操作
 */
public class UserDao {
    /**
     * 通过名称获取用户信息
     * @return
     */
    public User selectByName(String name){
        //1. 获取链接
        //2. 拼接SQL
        //3. 执行SQL
        //4. 拼装执行的结果
        //5. 关闭连接
        Connection connection = DBUtils.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try{
            String sql = "select * from user where user_name = ? and delete_flag = 0";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                //"id"对应数据库的字段
                user.setId(resultSet.getInt("id"));
                user.setUserName(resultSet.getString("user_name"));
                user.setPassword(resultSet.getString("password"));
                user.setGithubUrl(resultSet.getString("github_url"));
                user.setDeleteFlag(resultSet.getInt("delete_flag"));
                //getTimeSTamp 可以获取到时分秒
                //getDate 获取到日期
                //getTime 获取时分秒
                user.setCreateTime(resultSet.getTimestamp("create_time"));
//                user.setUpdateTime(resultSet.getTimestamp("update_time"));
                return user;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtils.close(connection,statement,resultSet);
        }
        return null;
    }

    /**
     * 通过ID来获取用户信息
     * @return
     */
    public User selectById(Integer userId){
        Connection connection = DBUtils.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            String sql = "select * from user where id = ? and delete_flag=0";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUserName(resultSet.getString("user_name"));
                user.setPassword(resultSet.getString("password"));
                user.setGithubUrl(resultSet.getString("github_url"));
                user.setDeleteFlag(resultSet.getInt("delete_flag"));
                user.setCreateTime(resultSet.getTimestamp("create_time"));
//                user.setUpdateTime(resultSet.getTimestamp("update_time"));
                return user;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtils.close(connection,statement,resultSet);
        }
        return null;
    }
}
